#include <iostream>
#include <string>
#include "39OOP-usingClass.hpp"

// 两个构造函数,用于初始化类对象
DefineAClass::DefineAClass()
{
    std::cout << "Default Constructor called! " << std::endl;
    company = "no name";
    shares = 0;
    share_val = 0.0;
    total_val -= 0.0;
}

DefineAClass::DefineAClass(const std::string &co, long n, double pr)
{
    std::cout << "Constructor using " << co << " called" << std::endl;
    company = co;
    if (n < 0)
    {
        std::cout << "Number of shares can't be negative " << company << " shares set to 0" << std::endl;
        shares = 0;
    }else{
        shares = n;
    }
    share_val = pr;
    set_tot();
}

// 析构函数,用于释放类时的默认操作
DefineAClass::~DefineAClass(){
    std::cout << "Bye, " << company << " !" << std::endl;
}

void DefineAClass::buy(long num, double price){
    if (num < 0)
    {
        std::cout << "Number of shares purchased can't be negative. " << "Transaction is aborted" << std::endl;
    }
    else{
        shares += num;
        share_val = price;
        set_tot();
    }
}

void DefineAClass::sell(long num, double price){
    using std::cout;
    using std::endl;
    if (num < 0)
    {
        cout << "Number of shares sold can't be negative." << "Transaction is aborted" << std::endl;
    }else if (num > shares)
    {
        cout << "You can't sell more than you have" << "Transaction is aborted" << std::endl;
    }else{
        shares -= num;
        share_val = price;
        set_tot();
    }
}

void DefineAClass::update(double price){
    share_val = price;
    set_tot();
}

void DefineAClass::show(){
        // set format to #.###
    using std::cout;
    using std::ios_base;

    ios_base::fmtflags orig = cout.setf(ios_base::fixed,ios_base::floatfield);
    std::streamsize prec = cout.precision(3);

    // print function
    std::cout << "Company: " << company
              << "  Shares: " << shares << '\n'
              << "  Share Price: $" << share_val
              << "  Total Worth: $" << total_val << '\n';

    // restore original format
    cout.setf(orig,ios_base::floatfield);
    cout.precision(prec);
}
